
// 回调缓存
import { changeRoute, changeRouteExecute } from '../../router'
import { getLocalParam, hasOwnProp, jsonObject, createOID, jsonString } from '../utils/normalUtils'
import { initUserLoginInfo, appState, exitApp } from './appManager'
import RouteConst from '../../router/routeConst'

const callBackMap:any = {}

/**
 * 独立化下逻辑
 */
const embedState = {
    embedInit: false,
    embed: false,
    embedKey: '',
    embedType: '',
    embedSameDomain: false,
    code: ''
}

/**
 * 解析嵌入模式  “视图 是否同域 唯一值”
 */
export function initEmbedState(systemCode:string) {
    const embed = getLocalParam('m')
    if (!embed) return
    embedState.embed = true
    embedState.embedKey = ''
    embedState.code = systemCode
    // 旧版本
    if (embed === '1') {
        embedState.embedSameDomain = true
        embedState.embedType = '1'
    } else if (embed === '2') {
        embedState.embedSameDomain = false
        embedState.embedType = '1'
    } else if (embed.length > 3) {
         embedState.embedType = embed.charAt(0)
         embedState.embedSameDomain = embed.charAt(1) === '3'
         embedState.embedKey = embed.substring(2, embed.length)
    }
    // 嵌入模式 通用的跨域消息调用
    if (window.parent) window.addEventListener('message', parentMessageHandler)
    embedState.embedInit = true
    return embedState
}

/**
 * 嵌入模式通过 上级获取用户信息
 */
export async function initEmbedUserInfo() {
    let result:any = await callBackParentMessage('init')
    if (result && result.data) {
        result = result.data
        if (result.userData)result.userData = jsonObject(result.userData, null)
        if (result.menuData)result.menuData = jsonObject(result.menuData, null)
    }
    return result
}

/**
 * 调用父容器接口并返回数据
 * @type {{}}
 */
export function callBackParentMessage(type:any, data:any = null) {
    return new Promise((resolve, reject) => {
        if (!window.parent || window.parent === window) {
            resolve(null)
            return
        }
        callBackMap[type] = resolve
        window.parent.postMessage({ uuid: embedState.embedKey, type, data, sys: embedState.code || '' }, '*')
    })
}

/**
 * 调用父容器接口并返回数据
 * @type {{}}
 */
export function callParentMessage(type:any, data:any = null) {
    if (!window.parent || window.parent === window) return null
    window.parent.postMessage({ uuid: embedState.embedKey, type, data, sys: embedState.code || '' }, '*')
}

/**
 * 消息返回处理
 * @param ev
 */
function parentMessageHandler(ev:any) {
    if (!ev.data) return
    const result = ev.data
    const uuid = result.uuid
    const sys = result.sys
    const type = result.type
    if ((uuid && uuid !== embedState.embedKey) || (sys && sys !== embedState.code)) return
    if (type === 'changeRoute') {
        changeRouteHandler(result.data)
        return
    }
    if (hasOwnProp(callBackMap, type)) {
        callBackMap[type](result || {})
        delete callBackMap[type]
    }
}

/**
 * 切换路由
 * @param data{route:{path:"",token:"",query:any}}
 */
function changeRouteHandler(data:any) {
    console.log('====================changeRouteHandler====================>>>>', data)
    if (!data.route) return
    let path:any = data.route.path || ''
    if (path.indexOf(RouteConst.MAIN) !== 0)path = RouteConst.MAIN + path
    changeRouteExecute(path, data.route.query || null)
}


// #################################################################### embed view ##################################################
/**
 *
 * @param url
 * @param uuId
 * @param viewType
 * @param sameDomain
 */
export function createSysEmbedUrl(url:string, uuId:string, viewType = '1', sameDomain = false) {
    const arr = url.split('?')
    const params = `m=${viewType}${sameDomain ? '3' : '5'}${uuId}`
    if (arr.length > 1) arr[1] = params + '&' + arr[1]
    else arr.push(params)
    return arr.join('?')
}


// ############################################################## app #########################################################

export async function appEmbedInit() {
    // 获取初始化信息
    const initData:any = await initEmbedUserInfo()
    // 信息获取失败 跳401
    if (!initData || !initData.user) {
        changeRouteExecute(RouteConst.ERROR_403)
        return
    }
    // 初始化用户信息
    await initUserLoginInfo(initData.user, true, initData.userData || null, initData.menuData || null)
    // 如果设置了初始化路由跳转 否则 不跳转
    if (initData.route && initData.route.path) {
        changeRouteHandler({ route: initData.route })
    }
}
